package pers.cz.business;

import pers.cz.commons.upload.FileUploadLog;
import pers.cz.excel.PoiUtils;
import pers.cz.exception.ErrorCode;
import pers.cz.exception.GeneralException;
import pers.cz.mapper.FileUploadBusiMapper;
import pers.cz.mapper.TestCaseMapper;
import pers.cz.model.FileUploadBusi;
import pers.cz.model.TestCase;
import pers.cz.pub.AbstractBusiness;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 文件上传实现
 * @program: PostGirl-panent
 * @description: FileUploadBusiness
 * @author: Cheng Zhi
 * @create: 2021-03-10 10:08
 **/
public class FileUploadBusiness extends AbstractBusiness {

    /**
     * 文件入库
     * @param file
     * @return 变更数
     */
    public Integer upload(MultipartFile file, Integer userId) throws IOException {

        int count = 0;
        if (file.isEmpty()) {
            return count;
        }
        String fileName = file.getOriginalFilename();
        long soNbr = FileUploadLog.insertFileUploadBusi(fileName, userId, null);
        List<TestCase> listTestCases =  PoiUtils.excelToEntity(file, userId);

        try {
            count = this.getMapper().getBean(TestCaseMapper.class).batchInsert(listTestCases);
            uploadFileUploadBusi(soNbr, 1);
        } catch (Exception e) {
            uploadFileUploadBusi(soNbr, 2);
            throw new GeneralException(ErrorCode.FILE_UPLOAD_ERROR);
        }

        return count;
    }

    /**
     * 根据soNbr修改FileUploadBusi的处理状态
     * @param soNbr
     * @param type
     */
    public void uploadFileUploadBusi(Long soNbr, Integer type) {

        FileUploadBusi fileUploadBusi = new FileUploadBusi();
        fileUploadBusi.setSoNbr(soNbr);
        fileUploadBusi.setType(type);
        this.getMapper().getBean(FileUploadBusiMapper.class).updateByPrimaryKeySelective(fileUploadBusi);
    }

    /**
     * 根据soNbr获取文件名称
     * @param soNbr
     * @return
     */
    public String queryFileNameBySoNbr(Long soNbr) {

        return this.getMapper().getBean(FileUploadBusiMapper.class).selectByPrimaryKey(soNbr).getFileName();
    }
}
